package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.ExchangeInfo;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

public class ExchangeDaoImpl extends TempDao {

    public ExchangeInfo getExchangeInfo(String exchangeKey) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_exchange_key where exchangeKey=?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setString(1, exchangeKey);
            rs = call.executeQuery();
            while (rs.next()) {
                ExchangeInfo data = new ExchangeInfo();
                data.setExchangeKey(rs.getString("exchangeKey"));
                data.setType(rs.getInt("type"));
                data.setChannelId(rs.getInt("channelId"));
                data.setServerId(rs.getLong("serverId"));
                data.setReward(rs.getString("reward"));
                data.setStartTime(rs.getInt("startTime"));
                data.setEndTime(rs.getInt("endTime"));
                data.setUseTimes(rs.getInt("useTimes"));
                data.setDelete(rs.getBoolean("isDelete"));
                return data;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public boolean updateExchangeUseTimes(String exchangeKey) {
        String sql = "update t_s_exchange set useTimes=useTimes+1 where exchangeKey=?";
        getDb().setConnName(DbNameStrategy.getServerDb());
        Map<Integer, DbParameter> para = new HashMap<>();
        para.put(1, new DbParameter(Types.NVARCHAR, exchangeKey));
        return getDb().executeNoneQuery(sql, para) > -1;
    }
}
